package com.sysware.utils;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;

public class FileCopyUtil {

	public static int count = 0;
	
	public static void main(String[] args) {
		listFiles(new File("I:\\资料"));
	}

	private static File destParentFile = new File("G:\\software");

	private static String[] SUFFIX_NAMES = { "mp4", "avi", "rmvb", "mkv","wmv" };

	private static void listFiles(File file) {
		//if(count>100) return;
		if (file != null && file.isDirectory() && file.listFiles() != null) {
			for (File f : file.listFiles()) {
				listFiles(f);
			}
		} else if (file != null && file.isFile()
				&& ArrayUtils.contains(SUFFIX_NAMES, FilenameUtils.getExtension(file.getName()).toLowerCase())) {
			String fileName = file.getName();
			if(StringUtils.isNotEmpty(fileName) && fileName.length()<12) {
				fileName = file.getParentFile().getName()+"-"+fileName;
			}
			String ext = FilenameUtils.getExtension(file.getName()).toLowerCase();
			String newName = RandomStringUtils.randomNumeric(32);
			File destFile = new File(destParentFile.getAbsolutePath() + "/" + newName + "." + ext);
			try {
				System.out.println("将复制"+fileName);
				FileUtils.copyFile(file, destFile);
				System.out.println("复制完成"+fileName);
				JSONObject obj = new JSONObject();
				obj.put(destFile.getName(), fileName);
				writeLog(obj);
				System.out.println("将删除"+fileName);
				FileUtils.deleteQuietly(file);
				File parentFile = file.getParentFile();
				if(parentFile.isDirectory() && (parentFile.listFiles()==null || parentFile.listFiles().length<1)) {
					FileUtils.deleteDirectory(parentFile);
				}
				System.out.println("删除完成"+fileName);
				count++;
				System.out.println(count);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void writeLog(JSONObject obj) {
		if (!destParentFile.exists()) {
			destParentFile.mkdirs();
		}
		File logFile = new File(destParentFile.getAbsolutePath() + "/log.txt");
		try {
			FileUtils.write(logFile, obj.toJSONString() + "\n", "UTF-8", true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
